/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ecmascript/tests/test_helper.h"

#include "common_components/heap/w_collector/w_collector.h"
#include "common_components/heap/collector/collector_proxy.h"
#include "common_components/heap/heap_manager.h"
#include "common_components/heap/allocator/region_desc.h"
#include "common_components/base_runtime/base_runtime_param.h"
#include "ecmascript/mem/dynamic_object_operator.h"
#include "ecmascript/js_hclass.h"
#include "ecmascript/mem/tagged_object.h"

using namespace common;

namespace panda::test {
class WCollectorTest : public BaseTestWithScope<false> {};

std::unique_ptr<WCollector> GetWCollector()
{
    CollectorResources& resources = Heap::GetHeap().GetCollectorResources();
    Allocator& allocator = Heap::GetHeap().GetAllocator();
    
    return std::make_unique<WCollector>(allocator, resources);
}

class WCollectorMock : public WCollector {
public:
    explicit WCollectorMock(Allocator& allocator, CollectorResources& resources)
        : WCollector(allocator, resources) {}

    ~WCollectorMock() override = default;

    bool TryUpdateRefFieldMock(BaseObject* obj, RefField<>& field, BaseObject*& newRef)
    {
        return this->TryUpdateRefField(obj, field, newRef);
    }

    bool TryForwardRefFieldMock(BaseObject* obj, RefField<>& field, BaseObject*& newRef)
    {
        return this->TryForwardRefField(obj, field, newRef);
    }

    bool TryUntagRefFieldMock(BaseObject* obj, RefField<>& field, BaseObject*& target)
    {
        return this->TryUntagRefField(obj, field, target);
    }

    void EnumAndTagRawRootMock(common::ObjectRef& ref, RootSet& rootSet)
    {
        this->EnumAndTagRawRoot(ref, rootSet);
    }

    void DoGarbageCollectionMock()
    {
        this->DoGarbageCollection();
    }

    void ProcessWeakReferencesMock()
    {
        this->ProcessWeakReferences();
    }
};

std::unique_ptr<WCollectorMock> GetWCollectorMock()
{
    CollectorResources& resources = Heap::GetHeap().GetCollectorResources();
    Allocator& allocator = Heap::GetHeap().GetAllocator();
    
    return std::make_unique<WCollectorMock>(allocator, resources);
}

HWTEST_F_L0(WCollectorTest, DoGarbageCollectionTest0) {
    std::unique_ptr<WCollector> wcollector = GetWCollector();
    ASSERT_TRUE(wcollector != nullptr);

    std::unique_ptr<WCollectorMock> wcollectorMock = GetWCollectorMock();
    ASSERT_TRUE(wcollectorMock != nullptr);

    RuntimeParam runtimePara = BaseRuntimeParam::DefaultRuntimeParam();
    runtimePara.gcParam.enableStwGC = true;
    wcollectorMock->Init(runtimePara);

    Mutator::GetMutator()->SetMutatorPhase(GCPhase::GC_PHASE_MARK);
    Mutator::GetMutator()->SetSuspensionFlag(Mutator::SuspensionType::SUSPENSION_FOR_GC_PHASE);
    Mutator::GetMutator()->TransitionGCPhase(true);

    wcollectorMock->DoGarbageCollectionMock();
    EXPECT_EQ(wcollectorMock->GetGCPhase(), GCPhase::GC_PHASE_IDLE);
}

HWTEST_F_L0(WCollectorTest, TryUpdateRefFieldTest0) {
    std::unique_ptr<WCollector> wcollector = GetWCollector();
    ASSERT_TRUE(wcollector != nullptr);

    std::unique_ptr<WCollectorMock> wcollectorMock = GetWCollectorMock();
    ASSERT_TRUE(wcollectorMock != nullptr);

    HeapAddress addr = HeapManager::Allocate(sizeof(BaseObject), AllocType::MOVEABLE_OBJECT, true);
    BaseObject *obj = reinterpret_cast<BaseObject*>(addr);
    new (obj) BaseObject();

    RefField<false> field(obj);
    field.SetTargetObject(obj);
    EXPECT_EQ(field.GetTargetObject(), obj);
    BaseObject* newObj;

    EXPECT_FALSE(wcollectorMock->TryUpdateRefFieldMock(obj, field, newObj));
}

HWTEST_F_L0(WCollectorTest, TryUpdateRefFieldTest1) {
    std::unique_ptr<WCollectorMock> wcollectorMock = GetWCollectorMock();
    ASSERT_TRUE(wcollectorMock != nullptr);

    HeapAddress addr = HeapManager::Allocate(sizeof(BaseObject), AllocType::MOVEABLE_OBJECT, true);
    BaseObject *obj = reinterpret_cast<BaseObject*>(addr);
    new (obj) BaseObject();

    RegionDesc* region = RegionDesc::GetRegionDescAt(addr);
    region->SetRegionType(RegionDesc::RegionType::FROM_REGION);

    RefField<false> field(obj);
    field.SetTargetObject(obj);
    EXPECT_EQ(field.GetTargetObject(), obj);

    BaseObject* newObj;

    EXPECT_FALSE(wcollectorMock->TryUpdateRefFieldMock(obj, field, newObj));
    EXPECT_EQ(newObj, nullptr);

    region->SetRegionType(RegionDesc::RegionType::THREAD_LOCAL_REGION);
}

HWTEST_F_L0(WCollectorTest, TryUpdateRefFieldTest2) {
    std::unique_ptr<WCollectorMock> wcollectorMock = GetWCollectorMock();
    ASSERT_TRUE(wcollectorMock != nullptr);

    size_t allocSize = sizeof(BaseObject) + sizeof(BaseObject) + sizeof(BaseClass);
    HeapAddress addr = HeapManager::Allocate(allocSize, AllocType::MOVEABLE_OBJECT, true);

    RegionDesc* region = RegionDesc::GetRegionDescAt(addr);
    region->SetRegionType(RegionDesc::RegionType::FROM_REGION);

    BaseObject *obj = reinterpret_cast<BaseObject*>(addr);
    new (obj) BaseObject();

    size_t addrOffset = sizeof(BaseObject);
    BaseObject *objFwd = reinterpret_cast<BaseObject*>(addr + addrOffset);
    new (objFwd) BaseObject();

    addrOffset += sizeof(BaseObject);
    objFwd->SetFullBaseClassWithoutBarrier(reinterpret_cast<BaseClass *>(addr + addrOffset));

    ecmascript::DynamicObjectOperator dynamicObjOp;
    BaseObject::RegisterDynamic(reinterpret_cast<BaseObjectOperatorInterfaces *>(&dynamicObjOp));
    
    obj->SetForwardState(BaseStateWord::ForwardState::FORWARDING);
    obj->SetForwardingPointerAfterExclusive(objFwd);

    RefField<false> field(obj);
    field.SetTargetObject(obj);
    EXPECT_EQ(field.GetTargetObject(), obj);

    BaseObject* newObj;

    EXPECT_TRUE(wcollectorMock->TryUpdateRefFieldMock(obj, field, newObj));
    EXPECT_EQ(newObj, objFwd);

    region->SetRegionType(RegionDesc::RegionType::THREAD_LOCAL_REGION);
}

HWTEST_F_L0(WCollectorTest, TryUpdateRefFieldTest3) {
    std::unique_ptr<WCollectorMock> wcollectorMock = GetWCollectorMock();
    ASSERT_TRUE(wcollectorMock != nullptr);

    size_t allocSize = sizeof(BaseObject) + sizeof(BaseObject);
    HeapAddress addr = HeapManager::Allocate(allocSize, AllocType::MOVEABLE_OBJECT, true);
    
    RegionDesc* region = RegionDesc::GetRegionDescAt(addr);
    region->SetRegionType(RegionDesc::RegionType::FROM_REGION);

    BaseObject *obj = reinterpret_cast<BaseObject*>(addr);
    new (obj) BaseObject();

    size_t addrOffset = sizeof(BaseObject);
    BaseObject *objFwd = reinterpret_cast<BaseObject*>(addr + addrOffset);
    new (objFwd) BaseObject();

    addrOffset += sizeof(BaseObject);
    objFwd->SetFullBaseClassWithoutBarrier(reinterpret_cast<BaseClass *>(addr + addrOffset));

    ecmascript::DynamicObjectOperator dynamicObjOp;
    BaseObject::RegisterDynamic(reinterpret_cast<BaseObjectOperatorInterfaces *>(&dynamicObjOp));
    
    obj->SetForwardState(BaseStateWord::ForwardState::FORWARDING);
    obj->SetForwardingPointerAfterExclusive(objFwd);

    RefField<false> field(obj);
    field.SetTargetObject(obj);
    EXPECT_EQ(field.GetTargetObject(), obj);

    BaseObject* newObj;

    EXPECT_TRUE(wcollectorMock->TryUpdateRefFieldMock(nullptr, field, newObj));
    EXPECT_EQ(newObj, objFwd);

    region->SetRegionType(RegionDesc::RegionType::THREAD_LOCAL_REGION);
}

HWTEST_F_L0(WCollectorTest, TryForwardRefFieldTest0) {
    std::unique_ptr<WCollectorMock> wcollectorMock = GetWCollectorMock();
    ASSERT_TRUE(wcollectorMock != nullptr);

    Mutator::GetMutator()->SetMutatorPhase(GCPhase::GC_PHASE_PRECOPY);

    HeapAddress addr = HeapManager::Allocate(sizeof(BaseObject), AllocType::MOVEABLE_OBJECT, true);
    BaseObject *obj = reinterpret_cast<BaseObject*>(addr);
    new (obj) BaseObject();

    obj->SetForwardState(BaseStateWord::ForwardState::FORWARDED);

    ecmascript::DynamicObjectOperator dynamicObjOp;
    BaseObject::RegisterDynamic(reinterpret_cast<BaseObjectOperatorInterfaces *>(&dynamicObjOp));

    RegionDesc* region = RegionDesc::GetRegionDescAt(addr);
    region->SetRegionType(RegionDesc::RegionType::FROM_REGION);

    RefField<false> field(obj);
    field.SetTargetObject(obj);
    EXPECT_EQ(field.GetTargetObject(), obj);

    BaseObject* newObj;

    EXPECT_FALSE(wcollectorMock->TryForwardRefFieldMock(obj, field, newObj));
    EXPECT_EQ(newObj, nullptr);

    region->SetRegionType(RegionDesc::RegionType::THREAD_LOCAL_REGION);
}

} // namespace panda::test